
import sys
import intergenicIntervals

NODE_SIZE = 100000
EXTENDER = 10000

def getNodes(chr, spos, epos, seq, seqId):
    nodes = []
    for x in xrange(int((spos-EXTENDER)/(1.0*NODE_SIZE)), int((epos+EXTENDER)/(1.0*NODE_SIZE))+1):
        nodes.append((chr, x, spos, epos, seq, seqId))
    return nodes

def addLinks(links, n1, n2, details=None):
    for node1 in n1:
        for node2 in n2:
            key = [node1, node2]
            key.sort()
            shortkey = ((key[0][0], key[0][1]), (key[1][0], key[1][1]))
            links[shortkey] = links.get(shortkey, 0) + 1
            if details != None:
                d = details.get(shortkey, [key[0][0], key[0][2], key[0][3], {}, key[1][0], key[1][2], key[1][3], {}])
                d[1] = min(d[1], key[0][2])
                d[2] = max(d[2], key[0][3])
                d[3][key[0][5]] = (key[0][2], key[0][3], key[0][4])
                d[5] = min(d[5], key[1][2])
                d[6] = max(d[6], key[1][3])
                d[7][key[1][5]] = (key[1][2], key[1][3], key[1][4])
                details[shortkey] = d

def buildGraph(file):
    links = {}
    details = {}
    n = 0
    for line in open(file):
        n += 1
        cols = line.strip().split("\t")
        # 3:23:648:804 PAIR-CHR chr1 - 981019 981050 AGCTCGT... chr7 - 24295671 24295702 ACGCGT...
        if cols[1]=="FIRST" or cols[1]=="SECOND":
            continue
        n1 = getNodes(cols[2], long(cols[4]), long(cols[5]), cols[6], cols[0] + "/1")
        n2 = getNodes(cols[7], long(cols[9]), long(cols[10]), cols[11], cols[0] + "/2")
        oldsize = len(links)
        addLinks(links, n1, n2, details)
        if len(links)>oldsize and 0 == len(links)%100:
            print >> sys.stderr, "# Links matrix has size ", len(links), " ; read ", n, " lines"
    return (links, details)

if __name__=="__main__":
    geneAnnotation = intergenicIntervals.getAllGeneLabels(5000)
    (links, details) = buildGraph(sys.argv[1])
    for (n1,n2) in links.keys():
        d = ""
        if details.has_key((n1,n2)):
            (chr1, spos1, epos1, seqs1, chr2, spos2, epos2, seqs2) = tuple(details[(n1,n2)])
            genes1 = "/".join(geneAnnotation[chr1].getLabels((spos1,epos1)).keys())
            genes2 = "/".join(geneAnnotation[chr2].getLabels((spos2,epos2)).keys())
            if genes1=="": genes1 = "Intergenic"
            if genes2=="": genes2 = "Intergenic"
            d = "%s:%ld-%ld\t%s\t%s:%ld-%ld\t%s" % (chr1, spos1, epos1, genes1, chr2, spos2, epos2, genes2)
        print "%s\t%ld\t%s\t%ld\t%d\t%s" % (n1[0], n1[1], n2[0], n2[1], links[(n1,n2)], d)
        if details.has_key((n1,n2)) and (chr1!=chr2 or abs(n1[1]-n2[1])>1):
            for seqId1 in seqs1.keys():
                if seqId1.endswith("/1"):
                    seqId2 = seqId1.replace("/1", "/2")
                else:
                    seqId2 = seqId1.replace("/2", "/1")
                (start1, end1, seq1) = seqs1[seqId1]
                (start2, end2, seq2) = seqs2[seqId2]
                print "%s\t%s:%ld-%ld\t%s" % (seqId1, chr1, start1, end1, seq1)
                print "%s\t%s:%ld-%ld\t%s" % (seqId2, chr2, start2, end2, seq2)
